package com.team.lostProperty.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.team.lostProperty.entity.PushInfo;
import com.team.lostProperty.entity.Result;
import com.team.lostProperty.entity.Type;
import com.team.lostProperty.entity.User;
import com.team.lostProperty.service.PushInfoService;
import com.team.lostProperty.utils.FileUpload;
import com.team.lostProperty.utils.TimeUtil;
import com.team.lostProperty.utils.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author duzq
 * @date 2020/07/22 14:24
 **/
@RestController
@RequestMapping("/pushInfo")
public class PushInfoController {

    @Autowired
    private PushInfoService pushInfoService;

    Result result = new Result();

    @CrossOrigin
    @RequestMapping("/obtainPushInfo")
    private Result obtainPushInfo(String status,String lastType,String page, String limit){
        List<PushInfo> pushInfo = pushInfoService.obtainPushInfo(Integer.valueOf(status),Integer.valueOf(lastType),Integer.valueOf(page),Integer.valueOf(limit));
        if (pushInfo.size()>=0){
            Gson gson=new Gson();
            String strPushInfo=gson.toJson(pushInfo);
            result.setCode(0);
            result.setMsg("成功");
            result.setCount(pushInfoService.getPushInfoCount(Integer.valueOf(status),Integer.valueOf(lastType)));
            result.setData(strPushInfo);
        }else{
            result.setCode(1);
            result.setMsg("失败");
            result.setCount(0);
            result.setData("");
        }
        return result;
    }

    /**
     * 获取发布的信息
     * @param status
     * @param page
     * @param limit
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/getPushInfo")
    private Result getPushInfo(String status, String page, String limit){
        List<PushInfo> pushInfo = pushInfoService.getPushInfo(Integer.valueOf(status),Integer.valueOf(page),Integer.valueOf(limit));
        if (pushInfo.size()>=0){
            result.setCode(0);
            result.setMsg("成功");
            result.setCount(pushInfoService.getAllCount(Integer.valueOf(status)));
            result.setData(pushInfo);
        }else{
            result.setCode(1);
            result.setMsg("失败");
            result.setCount(0);
            result.setData("");
        }
        return result;
    }

    /**
     * 根据条件查询发布信息
     * @param request
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/selectPushInfo")
    private Result selectPushInfo(HttpServletRequest request){
        String status = request.getParameter("status");
        PushInfo pushInfo = new PushInfo();
        User user = new User();
        if (!request.getParameter("id").equals("")){
            pushInfo.setPushInfoId(Integer.valueOf(request.getParameter("id")));
        }
        user.setUserName(request.getParameter("author"));
        pushInfo.setUser(user);
        pushInfo.setTitle(request.getParameter("title"));
        pushInfo.setPhone(request.getParameter("phone"));
        pushInfo.setStatus(Integer.valueOf(status));

        List<PushInfo> pushInfoList = pushInfoService.selectPushInfo(pushInfo);
        if (pushInfoList.size() >= 0){
            result.setCode(0);
            result.setMsg("成功");
            result.setData(pushInfoList);
            result.setCount(pushInfoService.getAllCount(Integer.valueOf(status)));
        }else{
            result.setCode(1);
            result.setMsg("失败");
            result.setData("");
            result.setCount(0);
        }
        return result;
    }

    // 根据id获取发布信息
    @CrossOrigin
    @RequestMapping("/selectById")
    private Result getPushInfoById(@RequestParam Map<String,String> idMap){
        int id=Integer.parseInt(idMap.get("id"));
        PushInfo pushInfo = pushInfoService.getPushInfoById(id);
        Gson gson=new Gson();
        String date= gson.toJson(pushInfo);
        if (pushInfo!=null){
            result.setCode(0);
            result.setMsg("成功");
            result.setData(date);
            result.setCount(1);
        }else{
            result.setCode(1);
            result.setMsg("失败");
            result.setData("");
            result.setCount(0);
        }
        return result;
    }

    private Result getPushInfoById(long pushInfoId){
        PushInfo pushInfo = pushInfoService.getPushInfoById(pushInfoId);
        Gson gson=new Gson();
        String date= gson.toJson(pushInfo);
        if (pushInfo!=null){
            result.setCode(0);
            result.setMsg("成功");
            result.setData(date);
            result.setCount(1);
        }else{
            result.setCode(1);
            result.setMsg("失败");
            result.setData("");
            result.setCount(0);
        }
        return result;
    }

    /**
     * 根据ID删除发布的信息
     * @param ids
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/deletePushInfo")
    private Result deletePushInfo(String ids){
        int i = 0;
        if (ids != null && !ids.equals("")) {
            String[] str = ids.split(",");
            for (String id : str) {
                if (id != null && !id.equals("")) {
                    i = pushInfoService.deletePushInfo(Integer.valueOf(id));
                }
            }
        }
        if (i > 0){
            result.setCode(0);
            result.setMsg("成功");
            result.setData("");
        }else{
            result.setCode(1);
            result.setMsg("失败");
            result.setData("");
        }
        return result;
    }

    /**
     * 根据ID删除发布的信息
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/deletePushById/{pushInfoId}")
    private Result deletePushInfo(@PathVariable("pushInfoId")int pushInfoId){
        int i = pushInfoService.deletePushInfo(Integer.valueOf(pushInfoId));
        if (i > 0){
            result.setCode(0);
            result.setMsg("成功");
            result.setData("0");
        }else{
            result.setCode(1);
            result.setMsg("失败");
            result.setData("1");
        }
        return result;
    }

    /**
     * 根据ID修改发布状态
     * @param pushInfoId
     * @param status
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/updatePushInfo")
    private Result updatePushInfo(int pushInfoId,int status){
        int i = pushInfoService.updatePushInfo(status,pushInfoId);

        if (i > 0){
            result.setCode(0);
            result.setMsg("成功");
            result.setData("");
        }else{
            result.setCode(1);
            result.setMsg("失败");
            result.setData("");
        }
        return result;
    }

    /**
     * 根据用户获取发布信息
     * @param userId
     * @param start
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/getUserPushInfo/{userId}/{start}")
    private String getUserPushInfo(@PathVariable("userId") long userId, @PathVariable("start") int start) {
        start = start * 10;
        /*if (start >= pushInfoService.getUserPushInfo(userId, start).size()){
            result.setCode(0);
            result.setMsg("成功");
            result.setCount(0);
            result.setData("noMore");
            return JSON.toJSONString(result);
        }*/
        List<PushInfo> pushInfoList = pushInfoService.getUserPushInfo(userId, start);
        if (pushInfoList.size() >= 0) {
            result.setCode(0);
            result.setMsg("成功");
            result.setCount(pushInfoList.size());
            result.setData(pushInfoList);
        } else {
            result.setCode(1);
            result.setMsg("失败");
            result.setCount(0);
            result.setData("");
        }
        return JSON.toJSONString(result);
    }

    /**
     * 根据用户获取发布信息
     * @param userId
     * @param page
     * @param limit
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/getUserPushInfo")
    private String getUserPushInfo(String userId,int page,int limit) {
        List<PushInfo> pushInfoList = pushInfoService.getUserPushInfo(Long.valueOf(userId), page, limit);
        if (pushInfoList.size() >= 0) {
            result.setCode(0);
            result.setMsg("成功");
            result.setCount(pushInfoService.getAllCount(0));
            result.setData(pushInfoList);
        } else {
            result.setCode(1);
            result.setMsg("失败");
            result.setCount(0);
            result.setData("");
        }
        return JSON.toJSONString(result);
    }

    /**
     * 根据标题模糊查询信息
     * @param map
     * @param start
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/getByTitle/{start}")
    private String getByTitle(@PathVariable("start") int start,@RequestParam Map<String,Object> map) {
        start = start * 10;
        if (start >= pushInfoService.getAllCount(0)){
            result.setCode(0);
            result.setMsg("成功");
            result.setCount(0);
            result.setData("noMore");
            return JSON.toJSONString(result);
        }
        List<PushInfo> pushInfoList = pushInfoService.getByTitle((String) map.get("title"), start);
        if (pushInfoList.size() >= 0) {
            result.setCode(0);
            result.setMsg("成功");
            result.setCount(pushInfoList.size());
            result.setData(pushInfoList);
        } else {
            result.setCode(1);
            result.setMsg("失败");
            result.setCount(0);
            result.setData("");
        }
        return JSON.toJSONString(result);
    }

    /**
     * 模糊查询信息
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("/getByContent")
    private Result getByContent(String content, String page, String limit){
        List<PushInfo> pushInfo = pushInfoService.getByContent(content,Integer.valueOf(page),Integer.valueOf(limit));
        if (pushInfo.size()>=0){
            result.setCode(0);
            result.setMsg("成功");
            result.setCount(pushInfo.size());
            result.setData(pushInfo);
        }else{
            result.setCode(1);
            result.setMsg("失败");
            result.setCount(0);
            result.setData("");
        }
        return result;
    }

    /**
     * 安卓发布信息
     * @param request
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("addpushInfo")
    public Result addpushInfo(HttpServletRequest request) {
        String adddata = request.getParameter("adddata");
        PushInfo pushInfo = JSON.parseObject(adddata, PushInfo.class);
        pushInfo.setCreatedDate(TimeUtil.getNowDetailedTime());

        try {
            pushInfoService.insertPushInfo(pushInfo);
            result.setData("success");
            result.setCount(1);
            result.setCode(Result.RESULT_OK);
            result.setMsg("帖子发布成功");
            return result;
        }catch (Exception e){
            result.setData("error");
            result.setCount(0);
            result.setCode(Result.RESULT_ERROR);
            result.setMsg("帖子发布失败");
            return result;
        }
    }

    /**
     * web发布信息
     * @param request
     * @return Result
     */
    @CrossOrigin
    @RequestMapping("webaddpushInfo")
    public Result webaddpushInfo(HttpServletRequest request) {
        String adddata = request.getParameter("adddata");
        JSONObject jsonObj = JSONObject.parseObject(adddata);
        String stitle = jsonObj.get("title").toString();
        String scontent = jsonObj.get("content").toString();
        String lastType =jsonObj.get("lastType").toString();
        int slastType=Integer.valueOf(lastType);
        String sphone = jsonObj.get("phone").toString();
        String atype =jsonObj.get("type").toString();
        int stype = Integer.valueOf(atype);
        String saddress = jsonObj.get("address").toString();
        Long userId = Long.valueOf(jsonObj.get("userId").toString());

        PushInfo pushInfo = new PushInfo();
        pushInfo.setTitle(stitle);
        pushInfo.setContent(scontent);
        pushInfo.setLastType(slastType);
        pushInfo.setPhone(sphone);
        pushInfo.setStatus(2);
        pushInfo.setLikeNumber(0);
        pushInfo.setAddress(saddress);
        pushInfo.setCreatedDate(TimeUtil.getNowDetailedTime());
        Type type = new Type();
        type.setTypeId(stype);
        User user = new User();
        user.setUserId(userId);
        pushInfo.setUser(user);
        pushInfo.setType(type);
        try {
            pushInfoService.insertPushInfo(pushInfo);
            result.setData("success");
            result.setCount(1);
            result.setCode(Result.RESULT_OK);
            result.setMsg("帖子发布成功");
            return result;
        }catch (Exception e){
            result.setData("error");
            result.setCount(0);
            result.setCode(Result.RESULT_ERROR);
            result.setMsg("帖子发布失败");
            return result;
        }
    }

    /**
     *上传图片
     * @param request
     * @return Result
     * @throws Exception
     */
    @CrossOrigin
    @RequestMapping("multipartAction")
    public Result multipartAction(HttpServletRequest request) throws Exception {
        FileUpload.springUpload(request);
        return result;

    }

    @CrossOrigin
    @RequestMapping("/imageUpload")
    public Result imageUpload(MultipartFile file, HttpServletRequest request)  {
        String dic = request.getParameter("dic");
        Result result= UploadUtil.fileSave(file,request,dic);
        return result;

    }
}
